package com.itobase.statusDetect.Service.impl;

import com.itobase.statusDetect.Model.Time;
import com.itobase.statusDetect.Repository.TimeRepository;
import com.itobase.statusDetect.Service.TimeService;
import com.itobase.statusDetect.Util.Message;
import com.itobase.statusDetect.Util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author htyu
 * @date 2019/2/24
 */
@Service
public class TimeServiceImpl implements TimeService {

    @Autowired
    TimeRepository timeRepository;


    @Override
    public List<Time> getList(String keyword) {
        List<Time> list = timeRepository.findAll();
        List<Time> result;
        if(StringUtils.isNotEmpty(keyword)){
            result = list.stream().filter(time ->
                            time.getSchoolYear().contains(keyword)||
                            time.getStartDate().contains(keyword)||
                            time.getTerm().contains(keyword))
                    .collect(Collectors.toList());
        }else{
            result = list;
        }
        return result;
    }

    @Override
    public Message create(Time time) {
        if(checkExist(time)){
            return Message.error("学期已存在，请勿重复");
        }else{
            return Message.success(timeRepository.save(time));
        }
    }

    @Override
    public Message update(Time time){
        if(checkExist(time)){
            return Message.error("学期已存在，请勿重复");
        }else{
            Time time_new = timeRepository.findById(time.getId()).get();
            time_new.setSchoolYear(time.getSchoolYear());
            time_new.setStartDate(time.getSchoolYear());
            time_new.setTerm(time.getTerm());
            time_new.setWeeks(time.getWeeks());
            return Message.success(timeRepository.save(time_new));
        }
    }

    public boolean checkExist(Time time){
        List<Time> list = timeRepository.findAll();
        for(Time test: list){
            if(test.equals(time)){
                return true;
            }
        }
        return false;
    }


}
